<template>
  <div ref="pieChart" class="chart"></div>
</template>

<script>
import { ref, onMounted, watch, onUnmounted } from 'vue'
import * as echarts from 'echarts'

export default {
  name: 'PieChart',
  props: {
    data: {
      type: Array,
      required: true,
      default: () => []
    }
  },
  setup(props) {
    const pieChart = ref(null)
    let chart = null

    const initChart = () => {
      if (!pieChart.value) return
      
      chart = echarts.init(pieChart.value)
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center'
        },
        series: [
          {
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '16',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: props.data
          }
        ]
      }
      chart.setOption(option)
    }

    const updateChart = () => {
      if (chart) {
        chart.setOption({
          series: [{ data: props.data }]
        })
      }
    }

    watch(() => props.data, () => {
      updateChart()
    }, { deep: true })

    onMounted(() => {
      initChart()
      window.addEventListener('resize', () => {
        chart && chart.resize()
      })
    })

    onUnmounted(() => {
      if (chart) {
        chart.dispose()
        chart = null
      }
    })

    return {
      pieChart
    }
  }
}
</script>

<style scoped>
.chart {
  width: 100%;
  height: 100%;
}
</style> 